import { getAdminRequest, reviseAdminRequest } from '@/apis/admin'
import { layout, tailLayout } from '@/utils/contants'
import { phoneRule } from '@/utils/formRules'
import { Button, Form, Input, Modal, Table, message } from 'antd'
import { ColumnsType } from 'antd/es/table'
import React, { useEffect, useState } from 'react'

interface adminInfoType {
	username: string,
	password: string
	id: number,
	role: number,
	building: string,
	phone: string
}
const Admin: React.FC = () => {
	const [admin, setAdmin] = useState<adminInfoType[]>([])
	const [currentAdmin, setCurrentAdmin] = useState<adminInfoType>()
	const [open, setOpen] = useState<boolean>(false)
	const [form] = Form.useForm()
	const columns: ColumnsType<adminInfoType> = [
		{
			dataIndex: 'username',
			title: '用户名'
		},
		{
			dataIndex: 'password',
			title: '密码',
		},
		{
			dataIndex: 'phone',
			title: '联系电话'
		},
		{
			dataIndex: 'building',
			title: '楼栋'
		},
		{
			title: '操作',
			dataIndex: 'action',
			render: (_, record) => {
				return <>
					<Button type="primary" onClick={() => { opneModal(record) }}>
						修改
					</Button>
				</>
			}
		}
	]
	useEffect(() => {
		getAdmin()
	}, [])
	const getAdmin = () => {
		getAdminRequest().then((res: any) => {
			setAdmin(res.result)
		})
	}
	const opneModal = (ad: adminInfoType) => {
		setOpen(true)
		setCurrentAdmin(ad)
		form.setFieldsValue(ad)
	}
	const onCancel = () => {
		setOpen(false)
	}
	const onFinish = (value: adminInfoType) => {
		value.id = currentAdmin?.id as number
		reviseAdminRequest(value).then((res: any) => {
			message.success(res.message)
			getAdmin()
			onCancel()
		})
	}
	return <div className="adminWrap">
		<Table dataSource={admin} rowKey={(record) => record.id} columns={columns}>
		</Table>
		<Modal open={open} footer={null} onCancel={onCancel} title="修改车辆">
			<Form form={form} onFinish={onFinish} {...layout}>
				<Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
					<Input />
				</Form.Item>
				<Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
					<Input.Password />
				</Form.Item>
				<Form.Item label="电话" name="phone" rules={[phoneRule]}>
					<Input />
				</Form.Item>
				<Form.Item label="楼栋" name="building" rules={[{ required: true, message: '请输入楼栋' }]}>
					<Input />
				</Form.Item>
				<Form.Item {...tailLayout}>
					<Button type="primary" htmlType="submit">
						添加
					</Button>
					<Button htmlType="button" onClick={() => form.resetFields()}>
						重置
					</Button>
				</Form.Item>
			</Form>
		</Modal>
	</div>
}

export default Admin